package net.qanar.gwnewsfeed.reader;

import java.io.*;
import java.net.*;
import java.util.*;
import net.qanar.gwnewsfeed.*;

public class GotWReader extends Reader {
	private Collection<Item> items;
	private String link = "http://www.guildwars.com/community/guildweek/";
	
	{
		items = new ArrayList<Item>();
		
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new URL(link).openStream()));
			String line = br.readLine();
			while (line != null) {
				if (line.equals("<ul class=\"bullet-list\">")) {
					line = br.readLine();
					while (!line.equals("</ul>")) {
						String title = line.substring(line.indexOf(".php\">")+6, line.indexOf("</a>"));
						Date date = new Date(line.substring(line.indexOf("Date\">")+6, line.indexOf("</span>")));
						URL url = new URL("http://www.guildwars.com" + line.substring(line.indexOf("href=\"")+6, line.indexOf(".php\">")+4));
						//items.add(new Item(title,getContent(url), getName(), date));
						items.add(new Item(title,"<a href='" + url.toString() + "'>" + title + "</a>", getName(), date));
						line = br.readLine();						
					}
					break;
				}				
				line = br.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static String getContent(URL url) {
		String content = "";
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
			String line = br.readLine();
			while (line != null) {
				if (line.equals("<!-- Content //-->")) {
					line = br.readLine();
					while (!line.contains("Guild Nominations Accepted")) {
						line = line.replace("src=\"/images/", "src=\"http://www.guildwars.com/images/");
						content += "\n" + line;
						line = br.readLine();
					}
					break;
				}
				line = br.readLine();
			}
		} catch (Exception e) {}
		return content;
	}
	
	@Override
	public Collection<Item> getItems() {
		return items;
	}

	@Override
	public String getName() {
		return "Guild of the Week";
	}
}